import { createStore, createLogger, Store } from "vuex";
import { UserState } from './modules/user'
import user from "./modules/user";
import axios from "axios";

interface SelectCarListState {
  word: string;
  children: {
    CoverPhoto: string;
    MasterID: string;
    Name: string;
    Spelling: string;
    newTags: any;
    tagurl: string;
  }[];
}

export interface CommentState {
  nickname: string;
  avator: string;
  content: string;
  createTime: string;
  id: string;
}

export interface HomeListState {
  title: string;
  type: {
    rightImg?: string;
    urls?: string[];
    bigImg?: string;
  };
  count: number;
  id: string;
  comment: CommentState[];
}



export type HistoryListState = HomeListState;

export interface RootState {
  selectCarList: SelectCarListState[];
  homeList: HomeListState[];
  searchList: string[];
  user: UserState;
  historyList: HistoryListState[];
}

const store: Store<RootState> = createStore({
  modules: {
    user,
  },
  state: {
    selectCarList: [],
    homeList: [],
    searchList: JSON.parse(localStorage.getItem("searchList") || "[]"),
    historyList: JSON.parse(localStorage.getItem("historyList") || "[]"),
    // user: {
    //   isLogin: false,
    //   nickname: "",
    //   avator: "",
    //   username: "",
    //   token: localStorage.getItem("token") || "",
    // },
  },
  mutations: {
    // 设置selectCarList数据的唯一方法
    setSelectCarList(state, payload: SelectCarListState[]) {
      state.selectCarList = payload;
    },

    setHomeList(state, payload: HomeListState[]) {
      state.homeList = [...state.homeList, ...payload];
    },
    addSearchList(state, payload: string) {
      state.searchList.unshift(payload);
      state.searchList = [...new Set(state.searchList)];
    },
    clearSearchList(state) {
      state.searchList.length = 0;
    },
    addHistoryList(state, payload: HistoryListState) {
      if (!state.historyList.some((v) => v.id === payload.id))
        state.historyList.unshift(payload);
    },
    removeHistoryList(state, payload: HistoryListState) {
      state.historyList = state.historyList.filter((v) => v.id !== payload.id);
    },
  },
  actions: {
    async fetchSelectCarList(context) {
      const resp = await axios.get(
        "http://baojia.chelun.com/v2-car-getMasterBrandList.html"
      );

      const carList: SelectCarListState[] = [];
      // 将数据转化
      // [{ name: '安迪', Spelling: 'Aodi' }]
      // => [{ word: 'A', children: [{ name: '安迪', Spelling: 'Aodi' }] }]
      resp.data.data.forEach((v) => {
        const item = carList.find((item) => item.word === v.Spelling[0]);
        if (item) {
          item.children.push(v);
        } else {
          carList.push({
            word: v.Spelling[0],
            children: [v],
          });
        }
      });
      context.commit("setSelectCarList", carList);
    },
    async fetchHomeList(
      context,
      params: { pageCode: number; pageSize: number }
    ) {
      const resp = await axios.get("/api/home/list", { params });
      context.commit("setHomeList", resp.data.data);
      return resp.data;
    },
  },
  plugins: [createLogger()],
});

store.subscribe((mutations, state) => {
  localStorage.setItem("historyList", JSON.stringify(state.historyList));
  localStorage.setItem("token", JSON.stringify(state.user.token));
  localStorage.setItem("searchList", JSON.stringify(state.searchList));
});

export default store;
